package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.RandomUtil;
import com.atguigu.commonutils.Result;
import com.atguigu.msmservice.service.MsmService;

import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin//解决跨域问题
@Slf4j
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信方法
        @GetMapping("send/{phone}")
    public Result sendMsm(@PathVariable String phone){
        //1从redis获取验证码，如果获取到直接返回
        String codePhone = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(codePhone)){
            log.info("我执行没有啊");
            return Result.ok();
        }
        //2如果获取不到，进行阿里云发送
        //生成随机值，传递阿里云并进行发送
        String code = RandomUtil.getSixBitRandom();
        Map<String, Object> params = new HashMap<>();
        params.put("code",code);
        //调用service 发送短信的方法
        boolean isSend = msmService.send(phone,params);
        if (isSend){
            //发送成功后验证码放到redis里面，设置有效时间
            redisTemplate.opsForValue().set(phone,code,50,TimeUnit.HOURS);
            return Result.ok();

        } else {
            return Result.error().message("短信发送失败");
        }
    }

}
